<template>
	<view class="container">
		<view class="top-nav">
			<view :class="data.showIndex==1?'active':''" class="nav-item" @click="hanleClick(1)">购买份数</view>
			<view class="nav-item" :class="data.showIndex==2?'active':''" @click="hanleClick(2)">充值记录</view>
		</view>
		<view v-if="data.showIndex==1" class="pay-page">
			<!-- <u-cell-group class="bg-color">
        <u-cell title="充值账户" :value="data.memberInfo.member_cellphone"></u-cell>
      </u-cell-group> -->
			<view class="flex item mb-20">
				<view class="label">充值账户</view>
				<view class="value">
					{{ data.memberInfo.member_cellphone }}
				</view>
			</view>
			<view class="flex item pay-list mb-20">
				<view class="radio_item" @click="payIndex = index" :class="payIndex == index?'active':''"
					v-for="(item,index) in payList" :key="index">
					<view class="mb-20">
						<font class="price_num">{{item.price_format}}</font>元
					</view>
					<view>签署流量包 {{item.count}}份</view>
				</view>
				<!-- <view class="label">充值份数</view>
        <view class="value">
          <u-input v-model="data.form.count" type='number' inputAlign='right' fontSize='16' placeholder="请输入充值份数"
                   border="none">
            <template v-slot:suffix>
              <view>/份</view>
            </template>
          </u-input>
        </view> -->
			</view>
			<!-- <view class="total mb-20">￥{{ total }}</view> -->
			<u-radio-group v-model="data.form.pay_channel" placement="column" iconPlacement="right">
				<view class="pay-stype-cell " v-for="(item, index) in data.paymentChannel" :key="index">
					<view style="display: flex;align-items: center;">
						<view class="flex-1 flex item-center">
							<u-icon slot="icon" size="30" name="weixin-fill" color="#09BB07"></u-icon>
							<view>微信支付</view>
						</view>
						<u-radio shape="circle" size="20" :value="item.value" class="bottom-line" :name="item.value"
							:checked="data.form.pay_channel == item.value"></u-radio>
					</view>
				</view>
			</u-radio-group>
			<!-- <u-cell-group class="bg-color m-t-32">
         <label>
           <view slot="value">
             <u--input v-model="data.form.count" placeholder="请输入充值份数" border="none"></u--input>
           </view>
         </label>
       </u-cell-group> -->
			<!-- <u-radio-group v-model="data.form.pay_channel" placement="column"
                     iconPlacement="right" class="bg-color group-item"
                     style="">
        <label class="uni-list-cell uni-list-cell-pd" style="height: 100px;"
               v-for="(item, index) in data.paymentChannel"
               :key="index">
          <view style="display: flex;align-items: center;">
            <u-radio shape="circle" size="20" :value="item.value" class="bottom-line" :name="item.value"
                     :checked="data.form.pay_channel == item.value"></u-radio>
            <u-icon slot="icon" size="50" name="weixin-fill" color="#09BB07"></u-icon>

          </view>
        </label>

      </u-radio-group> -->
			<view class="flex bottom-button payment-but" v-if="data.wxUserInfo.mini_open_id">
				<u-button @click="payment" color="#4787F0" type="info" text="确认支付" class="custom-style"
					:customStyle="butStyle"></u-button>
			</view>
			<view v-else class="flex bottom-button payment-but">
				<u-button color="#4787F0" type="info" text="确认支付" class="custom-style" open-type='getPhoneNumber'
					@getphonenumber='ongetPhoneNumber' iconColor="" :customStyle="butStyle"></u-button>
			</view>
		</view>
		<view v-else>
			<view class="page-box">
				<view class="card p-l-r-32" style="margin-top: 100rpx;">
					<z-paging ref="paging" v-model="data.orderList" @query="queryOrder"
						:pagingStyle="{marginTop:'100rpx'}">
						<view class="card-body m-t-32 bg-color p-32" style="border-radius: 10rpx;"
							v-for="(item, index) in data.orderList" :key="index">
							<text
								style="display: block;color: rgba(0,0,0,0.9);margin-top: 16rpx;">购买份数：{{ item.count }}</text>
							<view class="flex justify-space-between">
								<text
									style="display: block;color: rgba(0,0,0,0.6);padding-top: 16rpx;">购买时间：{{ item.paid_at }}
								</text>
								<view
									style="width: 40rpx;height: 40rpx;border: 2rpx solid rgba(0,0,0,0.2);border-radius: 40rpx;line-height: 40rpx;display: flex;align-items: center;">
									<u-icon name="arrow-rightward" color="#999999" style="margin-left: 5rpx;"></u-icon>
								</view>
							</view>
						</view>
					</z-paging>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		memberWxMiniLogin,
		userWxMiniLogin,
		wxMiniInfo
	} from "../../api/module/login";
	import {
		arrayGet,
		goNav,
		goSwitchTab,
		msg
	} from "../../utils/common";
	import {
		butStyle,
		paymentIcon
	} from "../../utils/style";
	import {
		contractOrder,
		contractOrderPayment,
		contractTemplateList,
		getPackageList,
		packageOrder
	} from "../../api/module/contract";
	import {
		commonMemberInfo,
		getEnterpriseInfo,
		getMemberCertification,
		memberInfo,
		memberOrderList,
		memberUserInfo
	} from "../../api/module/mine";
	import UCell from "../../uni_modules/uview-plus/components/u-cell/u-cell.vue";
	import {
		useStore
	} from 'vuex';
	import {
		onShow,
		onLoad
	} from "@dcloudio/uni-app";
	import {
		reactive,
		ref,
		computed
	} from "vue";
	const paging = ref(null);
	const store = useStore()
	const payIndex = ref(0)
	const payList = ref([])
	const data = reactive({
		showIndex: 1,
		user_id: 0,
		form: {
			count: '',
			pay_channel: 'wx_lite',
		},
		total: '0.00',
		memberInfo: {},
		wxUserInfo: {},
		orderList: [],
		paging: ref(null),
		paymentChannel: [{
			value: 'wx_lite',
		}]
	});
	const total = computed(() => {
		return data.form.count ? data.form.count * 5 : '0.00'
	})
	const queryOrder = (pageNo, pageSize) => {
		let params = {
			page: pageNo,
			limit: pageSize,
			user_id: data.user_id,
			user_type: data.memberInfo.member_type,
		}
		memberOrderList(params).then(res => {
			paging.value.complete(res.data)
		});
	}
	const payment = () => {
		if (!data.memberInfo) {
			goNav('/pages/alogin/index');
			return;
		}
		// if (data.form.count < 1) { 
		// 	msg('请输入充值份数');
		// 	return;
		// }
		createOrder({
			user_id: data.memberInfo.member_id,
			user_type: data.memberInfo.member_type,
			open_id: data.wxUserInfo.mini_open_id,
			remark: '购买合同',
			// count: data.form.count,
			id: payList.value[payIndex.value].id,
			pay_channel: data.form.pay_channel,
		});
	}
	const ongetPhoneNumber = (e) => {
		const memberInfo = data.memberInfo;
		if (!memberInfo) {
			goNav('/pages/alogin/index');
			return;
		}
		const memberId = data.memberInfo.member_id;
		const encryptedCode = e.detail.code;
		const encryptedData = e.detail.encryptedData;
		const iv = e.detail.iv;
		wx.login({
			success(res) {
				if (res.code) {
					const code = res.code; // 获取到用户的code值
					const params = {
						member_id: memberId,
						code: code,
						encryptedData: encryptedData,
						encryptedCode: encryptedCode,
						iv: iv,
					};
					wxMiniInfo(params).then(response => {
						createOrder({
							open_id: response.mini_open_id,
							remark: '购买合同',
							// count: data.form.count,
							id: payList.value[payIndex.value].id,
							pay_channel: data.form.pay_channel,
						});
					})
				} else {
					console.log('登录失败！' + res.errMsg);
				}
			},
			fail(error) {
				console.log('登录失败！', error);
			}
		});
	}
	const createOrder = (params) => {
		packageOrder(params).then(response => {
			// let orderId = response.id;
			// contractOrderPayment({
			// 	order_id: orderId
			// }).then(response => {
			wx.requestPayment({
				'timeStamp': response.timeStamp,
				'nonceStr': response.nonceStr,
				'package': response.package,
				'signType': response.signType,
				'paySign': response.paySign,
				'success': function(res) {
					if (res.errMsg == 'requestPayment:ok') {
						msg('支付成功');
						goSwitchTab('/pages/my/index');
					}
				},
				'fail': function(res) {
					if (res.errMsg == 'requestPayment:fail cancel') {
						msg('取消支付');
					}
				},
				'complete': function(res) {
					
				}
			})
			// });
		});
	}
	onLoad(() => {
		if (store.state.userType == 1) {
			memberInfo().then(res => {
				data.memberInfo = res;
				data.user_id = res.member_id
			}).catch(err => {})
		} else {
			getEnterpriseInfo().then(res => {
				data.memberInfo = res;
				console.log(data.memberInfo, res.user_id);
				data.user_id = res.user_id
			}).catch(err => {
				console.log(err)
			})
		}
		getPackageList().then(res => {
			payList.value = res
		})
		commonMemberInfo({}).then(res => {
			data.member_id = arrayGet(res, 'member.id');
			memberUserInfo({
				member_id: arrayGet(res, 'member.id'),
			}).then(response => {
				data.wxUserInfo = response;
			});
		});
	})
	const hanleClick = (index) => {
		data.showIndex = index;
	}
</script>
<style lang="scss" scoped>
	.u-slot-value {
		color: #ff9900;
		font-size: 40rpx;
		font-weight: bold;
	}

	u-icon {
		margin: auto;
		/* 水平居中 */
	}

	.group-item {
		margin: 0 50rpx 0 0;
	}

	.left {
		display: flex;
		font-size: 15rpx;
		width: 100%;
	}

	.right {
		width: 100%;
		font-size: 15rpx;
		align-items: center;
	}

	.payment-but {
		position: fixed;
		bottom: 0;
		width: 100%;
	}

	.item-center {
		align-items: center;
	}

	.container {
		height: 100vh;
		background: #f1efef;

		.pay-page {
			font-size: 32rpx;

			.mb-20 {
				margin-bottom: 20rpx;
			}

			.item {
				padding: 22rpx 32rpx;
				background: #fff;

				.label {}

				.value {
					flex: 1;
					display: flex;
					justify-content: flex-end;
				}
			}

			.pay-list {
				justify-content: space-between;
				flex-wrap: wrap;
				padding: 30rpx 30rpx 0;

				.radio_item {
					font-size: 26rpx;
					padding: 30rpx 0;
					color: #999;
					background-color: #F5F5F5;
					width: 48%;
					margin-bottom: 30rpx;
					border-radius: 8rpx;
					text-align: center;

					.price_num {
						color: #333;
						font-size: 42rpx;
					}
				}

				.active {
					color: #333;
					background: rgba(71, 135, 240, 0.4);
				}
			}

			.line {
				margin: 0 32rpx;
				width: 100%;
				height: 1rpx;
				border-top: 2rpx solid #999;
			}

			.total {
				padding: 22rpx 32rpx;
				background: #fff;
				color: #ff9900;
				font-weight: 500;
				text-align: right;
			}

			.pay-stype-cell {
				padding: 22rpx 32rpx;
				background: #fff;
			}
		}
	}
</style>